import 'dart:io';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mobile_scanner/mobile_scanner.dart' as ms;
import 'package:google_ml_kit/google_ml_kit.dart' as gml;

import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../add/x_add_router.dart';

class ScanPage extends StatefulWidget {
  const ScanPage({Key? key}) : super(key: key);

  @override
  State<ScanPage> createState() => _ScanPageState();
}

// 混入 SingleTickerProviderStateMixin
class _ScanPageState extends State<ScanPage> with SingleTickerProviderStateMixin {
  late ms.MobileScannerController cameraController;
  bool isScanComplete = false;
  bool isTorchOn = false;
  String? errorMessage;
  double scanLinePosition = 0.0; // 扫描线位置（0.0-1.0）
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    cameraController = ms.MobileScannerController(
      torchEnabled: false,
      formats: [
        ms.BarcodeFormat.qrCode,

        ms.BarcodeFormat.ean13,
      ],
    );

    cameraController.torchState.addListener(() {
      setState(() {
        isTorchOn = cameraController.torchState.value == true;
      });
    });

    // 初始化扫描线动画控制器，使用混入的 TickerProvider
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..addListener(() {
      setState(() {
        scanLinePosition = _animationController.value;
      });
    })..repeat();

    _requestPermission();
  }

  @override
  void dispose() {
    _animationController.dispose();
    cameraController.dispose();
    super.dispose();
  }

  void _requestPermission() async {
    var status = await Permission.camera.status;
    if (!status.isGranted) {
      await Permission.camera.request();
    }
  }

  void _onBarcodeScanned(String code) {
    if (!isScanComplete) {
      setState(() {
        isScanComplete = true;
      });
      _animationController.stop();
      cameraController.stop();

      Navigator.of(context).pop(code);
      // NavigatorUtils.push(context, '${XAddRouter.addQrPage}');

    }
  }

  void _toggleFlash() {
    cameraController.toggleTorch();
  }

  Future<void> _pickImage() async {
    final picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);

    if (image != null) {
      try {
        final inputImage = gml.InputImage.fromFilePath(image.path);
        final barcodeScanner = gml.GoogleMlKit.vision.barcodeScanner();
        final List<gml.Barcode> barcodes = await barcodeScanner.processImage(inputImage);

        if (barcodes.isNotEmpty && barcodes.first.rawValue != null) {
          _onBarcodeScanned(barcodes.first.rawValue!);
        } else {
          setState(() {
            errorMessage = AppLocale.text('d_saomatianjia');
          });
          Future.delayed(const Duration(seconds: 2), () {
            setState(() {
              errorMessage = null;
            });
          });
        }
      } catch (e) {
        setState(() {
          errorMessage = AppLocale.text('d_shibieshibai');
        });
        Future.delayed(const Duration(seconds: 2), () {
          setState(() {
            errorMessage = null;
          });
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final scanBoxSize = MediaQuery.of(context).size.width * 0.7;

    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.close, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [

        ],
      ),
      body: Container(
        color: Colors.black,
        child: Stack(
          children: [
            ms.MobileScanner(
              controller: cameraController,
              fit: BoxFit.cover,
              onDetect: (capture) {
                final List<ms.Barcode> barcodes = capture.barcodes;
                for (final barcode in barcodes) {
                  if (barcode.rawValue != null) {
                    _onBarcodeScanned(barcode.rawValue!);
                    break;
                  }
                }
              },
            ),
            // 扫描框和提示
            Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    width: scanBoxSize,
                    height: scanBoxSize,
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: Colors.blue,
                        width: 2,
                      ),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        // 扫描线动画（从上到下）
                        if (!isScanComplete)
                          Positioned(
                            top: scanLinePosition * scanBoxSize,
                            left: 0,
                            right: 0,
                            child: Container(
                              height: 2,
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [Colors.transparent, Colors.blue, Colors.transparent],
                                  stops: [0.0, 0.5, 1.0],
                                ),
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 20),
                  Text(
                    AppLocale.text('d_duizhunerweimashibei'),
                    style: TextStyle(color: Colors.white, fontSize: 16),
                  ),


                  const SizedBox(height: 30),


                  Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Colors.transparent,
                      border: Border.all(
                        color: Colors.grey.withOpacity(0.4),
                        width: 0.8,
                      ),
                      borderRadius: BorderRadius.circular(6),
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), // 恢复适当的水平内边距
                    constraints: const BoxConstraints( // 新增约束限制最大宽度
                      maxWidth: 250, // 限制最大宽度为300像素，可以根据需要调整
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          width: 40,
                          height: 40,
                          decoration: BoxDecoration(
                            color: Colors.grey.withOpacity(0.2),
                            borderRadius: BorderRadius.circular(6),
                          ),
                          child: const Center(
                            child: Icon(
                              Icons.camera_alt,
                              color: Colors.white,
                              size: 20,
                            ),
                          ),
                        ),
                        const SizedBox(width: 15), // 适当增加图标和文字间距
                        Flexible(
                          child: Text(
                            AppLocale.text('d_duizhunerweimashibeidata'),
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 10,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                  ),


                  const SizedBox(height: 50),

                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // 手电筒按钮组
                      Column(
                        children: [
                          IconButton(
                            icon: Icon(isTorchOn ? Icons.flash_on : Icons.flash_off, color: Colors.white),
                            onPressed: _toggleFlash,
                          ),
                          Text(
                            AppLocale.text('d_shoudiantong'),
                            style: TextStyle(color: Colors.white, fontSize: 12),
                          ),
                        ],
                      ),
                      const SizedBox(width: 50),
                      // 相册按钮组
                      Column(
                        children: [
                          IconButton(
                            icon: const Icon(Icons.image, color: Colors.white),
                            onPressed: _pickImage,
                          ),
                          Text(
                            AppLocale.text('d_xiangce'),
                            style: TextStyle(color: Colors.white, fontSize: 12),
                          ),
                        ],
                      ),
                    ],
                  ),


                ],
              ),
            ),
            // 错误提示
            if (errorMessage != null)
              Positioned(
                bottom: 100,
                left: 0,
                right: 0,
                child: Center(
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    decoration: BoxDecoration(
                      color: Colors.red.withOpacity(0.8),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      errorMessage!,
                      style: const TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}